//////////////////////////////////////////////////////////
// Filename: main.cpp
// Author:   SSE4
// Date:     07/27/2012
//
// Description: as usual, main.cpp is the main source file
//              containing entry point called "main" which
//              is called first
//
//////////////////////////////////////////////////////////

#include "stdafx.hpp"
#include "error.hpp"

static const int clientWidth (640);
static const int clientHeigth(480);

int xPos(0);
int yPos(0);
static const int R(20);

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	LRESULT ret(0);
	switch (uMsg)
	{
	case WM_DESTROY :
		PostQuitMessage(0);
		break;
	case WM_PAINT :
		{
			PAINTSTRUCT ps = {0};
			HDC DC = BeginPaint(hWnd, &ps);
			Ellipse(DC, xPos - R, clientHeigth - yPos + R, xPos + R, clientHeigth - yPos - R);
			EndPaint(hWnd, &ps);
		}
		break;
	default :
		ret = DefWindowProc(hWnd, uMsg, wParam, lParam);
	}
	return ret;
}

int main()
{
	WNDCLASSEX wc     = {0};
	wc.cbSize         = sizeof(WNDCLASSEX);
	wc.style          = 0;
	wc.lpfnWndProc    = WndProc;
	wc.cbClsExtra     = 0;
	wc.cbWndExtra     = 0;
	wc.hInstance      = 0;
	wc.hIcon          = 0;
	wc.hCursor        = 0;
	wc.hbrBackground  = 0;
	wc.lpszMenuName   = 0;
	wc.lpszClassName  = _T("MADNESS");
	wc.hIconSm        = 0;
	if (0 == RegisterClassEx(&wc))
	{
		return Error_CanNotRegisterWindowClass;
	}
	DWORD style(WS_OVERLAPPEDWINDOW), styleex(0);
	int width(clientWidth), height(clientHeigth);
	RECT rect = {0, 0, width, height};
	if (AdjustWindowRectEx(&rect, style, false, styleex))
	{
		width = rect.right - rect.left;
		height = rect.bottom - rect.top;
	}
	HWND hWnd = CreateWindowEx(styleex, wc.lpszClassName, wc.lpszClassName, style, 
		(GetSystemMetrics(SM_CXSCREEN) - width) >> 1, 
		(GetSystemMetrics(SM_CYSCREEN) - height) >> 1, 
		width, 
		height, 
		0, 0, 0, NULL);
	if (0 == hWnd)
	{
		return Error_CanNotCreateWindow;
	}
	ShowWindow(hWnd, SW_SHOWNORMAL);
	UpdateWindow(hWnd);
	MSG msg;
	for (;;)
	{
		if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			if (WM_QUIT == msg.message)
			{
				break;
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			{
				// TODO : move code block to another place
				static BYTE state[256] = {0};
				GetKeyboardState(state);
				if (state['W'] & 0xF0) yPos++;
				if (state['A'] & 0xF0) xPos--;
				if (state['S'] & 0xF0) yPos--;
				if (state['D'] & 0xF0) xPos++;
			}
			InvalidateRect(hWnd, NULL, true);
			// TODO : wait-able timer for stable FPS
			Sleep(16);
		}
	}
	return static_cast<int>(msg.wParam);
}
